package unit6;

class UncorrectBankCount {
    private int count;//银行账户余额
    public int getCount() {
        return count;
    }
    public void setCount(int count) {
        this.count = count;
    }
    public void withdraw(int money) { //取钱
        String name = "[取款事务]：";
        System.out.println(name + "开始。");
        int value = getCount();
        System.out.println(name + "当前余额为" + value + "元。");
        sleep(100);//调用sleep方法，睡眠100毫秒后继续处理
        setCount(value - money);
        System.out.println(name + "取出100元，当前余额为" + getCount() +
                           "元。");
        System.out.println(name + "结束。");
    }
    public void deposit(int money) {//转账汇入
        String name = "[转帐事务]：";
        System.out.println(name + "开始。");
        int value = getCount();
        System.out.println(name + "当前余额为" + value + "元。");
        sleep(100);//调用sleep方法，睡眠100毫秒后继续处理
        setCount(value + money);
        System.out.println(name + "转入100元，当前余额为" + getCount() +
                           "元。");
        System.out.println(name + "结束。");
    }
    public void sleep(int time) {//线程睡眠
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
//测试
public class  Ex6_3_UncorrectBankCountTest {
    public static void main(String[] args) {
        final UncorrectBankCount count = new UncorrectBankCount();
        count.setCount(1000);
        System.out.println("银行事务模拟开始......");
        //直接创建线程对象，重写其run方法，并调用start开启线程
        new Thread("取款事务") {
            public void run() {
                count.withdraw(100);//取100元
            }
        } .start();
        count.sleep(50);//调用sleep方法，睡眠50毫秒后继续处理
        //直接创建线程对象，重写其run方法，并调用start开启线程
        new Thread("支票转帐事务") {
            public void run() {
                count.deposit(100);//转账100元
            }
        } .start();
    }
}
